<template>
  <el-drawer
    :visible.sync="dialogVisible"
    :before-close="handleDialogClose"
    :close-on-press-escape="false"
    :size="showMobilePage ? '80%' : 1000">
    <DialogTitle slot="title" title="模板说明">
      <template v-if="showEditBtn">
        <span v-if="!isEdit" class="edit-btn" @click="templateDescEdit">编辑 <i class="el-icon-edit-outline" /></span>
        <template v-else>
          <span class="edit-btn" style="margin-left: 16px" @click="onSaveTemplateDesc">保存</span>
          <span class="edit-btn" @click="onCancelTemplateDescEdit">取消</span>
        </template>
      </template>
    </DialogTitle>
    <div class="desc-container">
      <div v-if="!isEdit" class="template-desc" v-html="fileData.templateDesc ? formatDesc(fileData.templateDesc) : '暂无模板说明'"/>
      <el-input
        v-else
        v-model="templateContent"
        :autosize="{minRows: 3, maxRows: 6}"
        resize="none"
        style="font-size: 13px; margin-bottom: 16px"
        type="textarea"
        maxlength="500"
        placeholder="请输入模板说明，限制500字符"/>
    </div>
    <div class="dialog-content">
      <el-tooltip v-if="setContractTitle().length > 38" :open-delay="800" placement="top">
        <div slot="content" style="max-width: 400px;">{{ setContractTitle() }}</div>
        <DialogTitle :title="setContractTitle()" :class="isFill ? 'is-fill-title' : 'normal-title'" style="position: relative;">
          <div class="template-action-btn">
            <el-button v-if="isFill" :loading="downloadLoading" class="btn" size="small" type="info" style="margin-right: 10px" @click="onDownloadFile">下载</el-button>
            <el-button :loading="downloadLoading" class="btn" size="small" type="info" style="margin-right: 0" @click="downloadEmptyTemplate">下载空模板</el-button>
          </div>
        </DialogTitle>
      </el-tooltip>
      <DialogTitle v-else :title="setContractTitle()" style="position: relative;">
        <div class="template-action-btn">
          <el-button v-if="isFill" :loading="downloadLoading" class="btn" size="small" type="info" style="margin-right: 10px" @click="onDownloadFile">下载</el-button>
          <el-button :loading="downloadLoading" class="btn" size="small" type="info" style="margin-right: 0" @click="downloadEmptyTemplate">下载空模板</el-button>
        </div>
      </DialogTitle>
      <div class="template-box">
        <div v-loading="loading" class="template-content">
          <iframe id="fileIframe" :src="curPreviewFilePath" class="iframe-container" />
        </div>
      </div>
    </div>
    <div v-if="showFooter" class="dialog-footer">
      <el-button
        :disabled="changeTemplateBtnStatus(false)"
        :class="changeTemplateBtnStatus(false) ? 'disabled-btn' : 'empty-btn-style'"
        class="btn"
        type="primary"
        size="small"
        @click="changePreviewTemplate(false)">上一个</el-button>
      <el-button
        :disabled="changeTemplateBtnStatus(true)"
        :class="changeTemplateBtnStatus(true) ? 'disabled-btn' : 'empty-btn-style'"
        class="btn"
        type="primary"
        size="small"
        @click="changePreviewTemplate(true)">下一个</el-button>
    </div>
  </el-drawer>
</template>

<script>
import DialogTitle from '@/components/Title';
import { downloadFile } from '@/utils';
import { showModal } from '@/utils/message';
import { editTemplateDesc } from '@/api/legal';
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';

export default {
  name: 'ContractPreview',
  components: {
    DialogTitle
  },
  props: {
    fileData: {
      type: Object,
      default: () => ({})
    },
    fileList: {
      type: Array,
      default: () => []
    },
    previewPath: { // 预览文件地址
      type: String,
      default: ''
    },
    isFill: {
      type: Boolean,
      default: true
    },
    downloadLoading: {
      type: Boolean,
      default: false
    },
    showFooter: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      loading: false,
      dialogVisible: false,
      isEdit: false,
      templateContent: '',
      curPreviewFilePath: ''
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    showEditBtn() {
      return hasRouteAuth('crm:contract:templateDesc:edit');
    }
  },
  watch: {
    dialogVisible(status) {
      if (status) {
        this.loading = true;
        this.$nextTick(() => {
          this.formatIframeUrl();
          const iframeDom = document.querySelector('#fileIframe');
          if (iframeDom) {
            iframeDom.addEventListener('load', () => {
              this.loading = false;
            }, false);
          } else {
            this.loading = false;
          }
        });
      } else {
        this.curPreviewFilePath = '';
      }
    },
    previewPath(path) {
      if (path) {
        this.loading = true;
        this.formatIframeUrl();
      }
    }
  },
  methods: {
    formatIframeUrl() {
      if (!this.dialogVisible) return;
      if (this.isFill && !this.previewPath) {
        this.loading = true;
        return;
      }
      try {
        const url = this.isFill ? this.previewPath : this.fileData.filePath;
        const name = this.fileData.fileName;
        const timestamp = (new Date()).valueOf();
        const random = Math.ceil(Math.random() * 10);
        const lists = name && name.split('.');
        const fileName = `${timestamp}${random}.` + lists[lists.length - 1];
        const previewUrl = `${url}#&fullfilename=${fileName}`;
        const formatUrl = 'https://fileview.feibo.com/onlinePreview?url=' + encodeURIComponent(btoa(previewUrl));
        if (formatUrl && formatUrl === this.curPreviewFilePath) return;
        this.curPreviewFilePath = formatUrl;
      } catch (error) {
        console.log(error);
      }
    },
    // 模板填充换行
    formatDesc(str) {
      return str.replace(/\n/g, '<br>');
    },
    setContractTitle() {
      if (!this.fileData.fileName) {
        return '模板预览';
      }
      const fullFileName = this.fileData.fileName.split('.');
      fullFileName.pop();
      const fileName = fullFileName.join('.');
      return '模板预览:《' + fileName + '》';
    },
    changePreviewTemplate(isNext = true) {
      if (this.isEdit) {
        showModal('模板说明还未保存，确认切换吗？').then(_ => {
          this.isEdit = false;
          this.onPreviewTemplateChange(isNext);
        });
      } else {
        this.onPreviewTemplateChange(isNext);
      }
    },
    onPreviewTemplateChange(isNext = true) {
      this.loading = true;
      const fileArr = this.fileList.filter(file => !file.isFolder);
      const curFileIndex = fileArr.findIndex(item => item.id === this.fileData.id);
      const changeFile = isNext ? fileArr[curFileIndex + 1] : fileArr[curFileIndex - 1];
      this.$emit('setDownloadParams', changeFile, false);
      // 非填充模板直接改变url，填充模板根据监听previewPath改变
      this.$nextTick(() => {
        !this.isFill && this.formatIframeUrl();
      });
    },
    changeTemplateBtnStatus(isNext) {
      if (this.loading) return true;
      const fileArr = this.fileList.filter(file => !file.isFolder);
      const curFileIndex = fileArr.findIndex(item => item.id === this.fileData.id);
      if (curFileIndex !== -1) {
        return (isNext && curFileIndex === fileArr.length - 1) || (!isNext && curFileIndex === 0);
      } else {
        return true;
      }
    },
    templateDescEdit() {
      this.templateContent = this.fileData.templateDesc;
      this.isEdit = true;
    },
    onSaveTemplateDesc() {
      const params = Object.create(null);
      params.content = this.templateContent;
      params.id = this.fileData.id;
      editTemplateDesc(params).then(() => {
        this.fileData.templateDesc = this.templateContent;
        this.templateContent = '';
        this.isEdit = false;
        this.$message.success('保存成功');
      }).catch(() => {
        this.isEdit = false;
      });
    },
    onCancelTemplateDescEdit() {
      this.templateContent = '';
      this.isEdit = false;
    },
    handleDialogClose(callback) {
      if (this.isEdit) {
        this.cancelConfirm(callback);
      } else {
        this.dialogVisible = false;
      }
    },
    cancelConfirm(callback, title = '模板说明还未保存，确认取消吗？') {
      showModal(title).then(_ => {
        this.isEdit = false;
        this.dialogVisible = false;
        callback();
      });
    },
    // 下载空模板
    downloadEmptyTemplate() {
      downloadFile(this.fileData.filePath, this.fileData.fileName);
    },
    // 下载填充模板
    onDownloadFile() {
      this.$emit('setDownloadParams', this.fileData, true);
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-drawer__header {
  height: 48px;
  padding: 0 16px;
  margin: 0;
  box-shadow: none !important;
  > span {
    font-size: 16px;
    color: #333;
    font-weight: bold;
  }
}
::v-deep .el-drawer__body {
  padding: 0 16px 50px !important;
  height: calc(100vh - 48px);
  overflow-y: auto;
}
.template-desc {
  background-color: #f8f8f8;
  color: #666666;
  font-size: 12px;
  text-align: justify;
  padding: 8px 12px;
  margin-bottom: 16px;
}
.edit-btn {
  margin-left: 16px;
  color: #406eff;
  font-size: 14px !important;
  font-weight: normal;
  cursor: pointer;
}
.dialog-content {
  position: relative;
  ::v-deep .title-main {
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }
  .is-fill-title {
    ::v-deep .title-main {
      max-width: calc(100% - 185px);
    }
  }
  .normal-title {
    ::v-deep .title-main {
      max-width: calc(100% - 120px);
    }
  }
  .template-action-btn {
    position: absolute;
    right: 0;
  }
  .template-box {
    background-color: #f8f8f8;
    margin-top: 16px;
    padding: 8px;
    .template-content {
      background-color: #fff;
      .iframe-container {
        width:100%;
        min-height: 400px;
        height: calc(100vh - 200px);
        border: none;
        outline: none;
      }
    }
  }
}
.btn {
  font-size: 14px;
  padding: 7px 14px;
  margin-right: 16px;
  margin-left: 0;
}
.dialog-footer {
  height: 50px;
  width: 100%;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  background-color: #fff;
  border-top: 1px solid #eee;
  z-index: 5;
  .empty-btn-style {
    border-color: #406EFF;
    background: #fff;
    color: #406EFF;
    text-align: center;
    &:hover {
      background: #406EFF;
      color: #fff;
    }
  }
  .disabled-btn {

  }
}
</style>
